package com.redis.controller;

import com.redis.pojo.Redis;
import com.redis.service.impl.RedisServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class RedisController {

    @Autowired
    private RedisServiceImpl redisService;

    @RequestMapping(value = "/str", method = RequestMethod.GET)
    public void str() {
        List<Redis> redisList = redisService.findString();
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public void list() {
        List<Redis> redisList = redisService.findList();
    }

    @RequestMapping(value = "/set", method = RequestMethod.GET)
    public void set() {
        List<Redis> redisList = redisService.findSet();
    }

    @RequestMapping(value = "/hash", method = RequestMethod.GET)
    public void hash() {
        List<Redis> redisList = redisService.findHash();
    }

    @RequestMapping(value = "/zSet", method = RequestMethod.GET)
    public void zSet() {
        List<Redis> redisList = redisService.findZSet();
    }

    @RequestMapping(value = "/lock", method = RequestMethod.POST)
    public void lock(@RequestParam("Id") String Id) {

        secKill(Id);
    }

    //超时时间10s
    private static final int TIMEOUT = 10 * 1000;

    public void secKill(String productId){
        long time = System.currentTimeMillis() + TIMEOUT;
        //加锁
        if (!redisService.lock(productId, String.valueOf(time))){
            //throw new SellException(101, "人太多了，等会儿再试吧~");
            log.info("人太多了，等会儿再试吧~");
        }
        //具体的秒杀逻辑

        //解锁
        redisService.unlock(productId, String.valueOf(time));
    }
}
